from django.core.paginator import Paginator
from django.shortcuts import render
from django.db.models import Q

from common.models import Member

def index(request,pIndex):
    '''浏览信息'''
    umod = Member.objects
    mywhere = []
    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword", None)

    if kw:
        list = umod.filter(Q(nickname__contains=kw) | Q(mobile__contains=kw))
        mywhere.append("keyword=" + kw)
    else:
        list = umod.filter()
    print(mywhere)

    # 分页逻辑
    if pIndex == '':
        pIndex = '1'
    pIndex = int(pIndex)
    p = Paginator(list,3)
    maxpages = p.num_pages  # 最大页数

    # 判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1

    list2 = p.page(pIndex)
    plist = p.page_range

    context = {'usersList': list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages, 'mywhere': mywhere}
    return render(request,"myadmin/member/index.html",context)

def edit(request,uid):
    '''加载编辑页面信息'''
    try:
        ob = Member.objects.get(id = uid)
        context={"member":ob}
        return render(request,"myadmin/member/edit.html",context)
    except Exception as err:
        print(err)
        context = {"info":"没有找到会员信息！"}
        return render(request,"myadmin/info.html",context)

def update(request,uid):
    '''执行编辑信息'''
    try:
        ob = Member.objects.get(id = uid)
        ob.status = request.POST['status']
        ob.save()
        context = {"info":"修改成功！"}
    except Exception as err:
        print(err)
        context = {"info":"修改失败！"}
    return render(request,"myadmin/info.html",context)